<template>
	<div class="search">
		<div class="box">
			<input type="text" class="search-input" placeholder="输入城市名或者拼音" v-model="keyworld">
		</div>
		<div class="search-content  " ref="wrapper" v-show="keyworld">
			<ul>
				<li 
					v-for="item in list" 
					:key="item.id" 
					class="border-bottom"
					@click="changeCurrentCity(item.name)"
				>
					{{item.name}}
				</li>
				<li v-show="flag" class="border-bottom">对不起，找不到匹配的数据......</li>
			</ul>
		</div>
	</div>
</template>

<script>
	import {mapGetters} from 'vuex'
	import BScroll from '@better-scroll/core'
	//创建事件总线
	import Vue from 'vue'
	Vue.prototype.bus=new Vue()
	export default{
		data(){
			return{
				keyworld:'',
				list:[],
				timer:null,
				flag:false
			}
		},
		computed:{
			...mapGetters(['cities'])
		},
		mounted() {
		},
		updated() {
			//数据加载完成，可以进行初始化了
			this.$nextTick(() =>{
			 this.initNormal();
			});
		},
		watch:{
			keyworld(){
				//截流函数
				if(this.timer){
					clearTimeout(this.timer)
				}
				this.timer=setTimeout(()=>{
					const result=[]
					for (let i in this.cities){
						//对每个数组再做一个遍历
						this.cities[i].forEach((value)=>{
							if(value.spell.indexOf(this.keyworld)>-1 ||value.name.indexOf(this.keyworld)>-1){
								result.push(value)
							}
						})
					}
					this.list=result
					this.flag=!this.list.length
					//当输入框没东西的时候，就清空列表
					if(this.keyworld==''){
						this.list=[]
					}
				},100)
			}
		},
		methods:{
			//创建better-scroll
			initNormal(){
			   if (!this.scroll) {
			       this.scroll = new BScroll(this.$refs.wrapper, {
			           click: true,
			           probeType: 3,
			       });
			   } else {
			       this.scroll.refresh();
			   };
			},
			//选中城市
			changeCurrentCity(val){
				this.bus.$emit('functionEmit',val)
				this.keyworld=''
			}
		}
	}
</script>

<style lang="stylus" scoped>
	@import '../../assets/styles/varibles.styl'
	.search
		background-color :$bgColor
		color:#fff
		.box
			text-align center
			height 0.7rem
			margin 0 0.3rem
			.search-input
				box-sizing border-box
				width 100%
				font-size 0.25rem
				border-radius 0.05rem
				line-height 0.6rem
				padding 0 0.1rem
				color #666
		.search-content
			z-index 1
			overflow hidden
			position absolute
			top 1.33rem
			right 0
			bottom 0
			left 0
			background-color #eee
			li
				line-height .62rem
				padding-left 0.2rem
				color #666
				background #fff
</style>
	
